package net.p2pcdn.controller;

import com.qc.bean.result.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
@Slf4j
public class ExceptionController {

    // 捕捉shiro的异常
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(ShiroException.class)
    public ResponseData handle401(ShiroException e) {
        log.error(e.getMessage(), e);
        return ResponseData.error(e.getMessage(), 401);
    }

    // 捕捉UnauthorizedException
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(AuthenticationException.class)
    public ResponseData handle401(AuthenticationException e) {
        return ResponseData.error(e.getMessage(), 401);
    }

    // 捕捉UnauthorizedException
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(UnauthorizedException.class)
    public ResponseData handle401() {
        return ResponseData.error("您未登录或Session已过期", 401);
    }


    // 捕捉其他所有异常
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseData globalException(HttpServletRequest request, Throwable ex) {
        log.error(ex.getMessage(), ex);
        return ResponseData.error(ex.getMessage(), getStatus(request).value());
    }

    // 捕捉其他所有异常
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseData globalRuntimeException(HttpServletRequest request, Throwable ex) {
        log.error(ex.getMessage(), ex);
        return ResponseData.error(ex.getMessage(), getStatus(request).value());
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}
